<template>
  <div>
    <a-row type="flex" :gutter="16">
      <a-col :md="5" :sm="24">
        <a-card title="标签库" :bordered="false">
          <a-tree
            :autoExpandParent="true"
            :defaultExpandAll="true"
            :blockNode="true"
            showLine
            checkStrictly
            :replace-fields="replaceFields"
            :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
            :treeData="categoryList"
          >
            <template slot="custom" slot-scope="item">
              <div class="box" @click.stop="handleSelect(item)">
                <span>{{ item.categoryName }}</span>
                <a-icon
                  style="margin-left: 15px"
                  v-if="item.children"
                  type="plus"
                  @click.stop="handleAddTags(item.dataId)"
                />
                <a-icon style="margin-left: 5px" type="form" @click.stop="handleEditTags(item)" />
                <a-icon
                  style="margin-left: 5px"
                  v-if="!item.children || item.children.length == 0"
                  type="delete"
                  @click.stop="handleDeleteCheck2(item.dataId)"
                />
              </div>
            </template>
          </a-tree>
          <a-modal
            :visible="deleteVisible2"
            :centered="true"
            :confirm-loading="deleteLoading2"
            @ok="handleDelete2(dataId)"
            @cancel="handleDeleteCancel2"
            width="350px"
          >
            <span>确认删除此分类?</span>
          </a-modal>

          <category-modal ref="packageModalForm" @ok="packageModalFormOk"></category-modal>
        </a-card>
      </a-col>
      <a-col :md="24 - 5" :sm="24">
        <a-card :border="false">
          <div class="it_search">
            <a-form-model :form="form" layout="inline">
              <a-row>
                <a-col style="float: left"
                  ><a-button :style="{ marginBottom: '1rem' }" type="primary" @click="handleAddContent">
                    添加标签
                  </a-button></a-col
                >
                <a-col style="float: right">
                  <a-form-model-item label="分类">
                    <a-select
                      style="width:150px"
                      placeholder="请选择分类"
                      v-model="tagType"
                      @change="handleSelectChange"
                    >
                      <a-select-option v-for="item in list" :key="item.dataId" :value="item.dataId">
                        {{ item.categoryName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="标签">
                    <a-input v-model="tagName" />
                  </a-form-model-item>
                  <a-button type="primary" @click="search">
                    查询
                  </a-button>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
          <a-table
            :pagination="ipagination"
            :loading="loading"
            rowKey="tagId"
            :bordered="true"
            :columns="patientColumns"
            :data-source="tags"
            @change="handleTableChange"
          >
            <a slot="action" slot-scope="text, record">
              <a-button @click="handleEditContent(record)" style="margin-right:15px">编辑</a-button>
              <a-button @click="handleDeleteCheck(record.tagId)">删除</a-button>
            </a>
            <template slot="image" slot-scope="text, record">
              <div style="display: flex; justify-content: space-around; flex-wrap: wrap;" v-if="record.image">
                <div v-for="(photo, index) in record.image.split(',')" :key="index">
                  <img style="width: 50px; height: 50px;" :src="photo" :preview="record.image.split(',')" />
                </div>
              </div>
              <div v-else></div>
            </template>
          </a-table>
          <a-modal
            :visible="deleteVisible"
            :centered="true"
            :confirm-loading="deleteLoading"
            @ok="handleDelete(tagId)"
            @cancel="handleDeleteCancel"
            width="350px"
          >
            <span>确认删除此标签?</span>
          </a-modal>
          <a-modal title="预览" :visible="viewVisit" :confirm-loading="viewLoading" @cancel="viewCancel" width="700px">
            <p v-html="content"></p>
          </a-modal>

          <tag-modal ref="serviceModalForm" @ok="serviceModalFormOk"></tag-modal>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { getAction, postAction, deleteAction } from '@/api/manage'
import CategoryModal from './modules/CategoryModal'
import TagModal from './modules/TagModal'
import moment from 'moment'

const patientColumns = [
  {
    title: '标签',
    dataIndex: 'tagName',
    align: 'center'
  },
  {
    title: '栏目',
    dataIndex: 'tagTypeName',
    align: 'center'
  },
  {
    title: '热度',
    dataIndex: 'tagHot',
    width: 100,
    align: 'center'
  },
  {
    title: '操作',
    key: 'operation',
    width: 250,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: { CategoryModal, TagModal },
  data() {
    return {
      loading: true,
      viewLoading: false,
      viewVisit: false,
      deleteVisible: false,
      deleteLoading: false,
      deleteVisible2: false,
      deleteLoading2: false,
      type: undefined,
      dataId: '',
      content: '',
      tagType: '',
      tagName: '',
      replaceFields: {
        children: 'children',
        title: 'categoryName'
      },
      categoryList: [
        {
          dataId: 17,
          categoryName: '患者'
        },
        {
          dataId: 18,
          categoryName: '内容'
        }
      ],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      categoryParams: {
        pageNum: 1,
        pageSize: 10
      },
      patientColumns,
      tags: [],
      title: '',
      form: this.$form.createForm(this),
      activeGroupId: 17,
      list: []
    }
  },
  watch: {
    activeGroupId() {
      this.categoryParams.pageNum = 1
    }
  },
  created() {
    this.getTagGroups()
    this.getCategory()
    this.getTags()
  },
  methods: {
    handleSelectChange() {
      console.log(this.tagType)
    },
    getTagGroups() {
      postAction('tag/category/list', {}).then(res => {
        if (res.success) {
          this.list = res.result.filter(v => {
            return v.categoryPid == 17 || v.categoryPid == 18
          })
        } else {
          console.log(res.message)
        }
      })
    },
    getCategory() {
      postAction('tag/category/list', {}).then(res => {
        if (res.success && res.result) {
          this.categoryList = this.categoryList.map(v => {
            const children = res.result.filter(n => {
              return n.categoryPid == v.dataId
            })
            const curr = {
              dataId: v.dataId,
              categoryName: v.categoryName,
              children: children.map(item => {
                return {
                  ...item,
                  scopedSlots: {
                    title: 'custom'
                  }
                }
              }),
              scopedSlots: {
                title: 'custom'
              }
            }
            return curr
          })
          this.ipagination.total = res.result.length
        } else {
          console.log(res.message)
        }
      })
    },
    getTag() {
      this.loading = true
      postAction('tag/list', { tagType: this.activeGroupId })
        .then(res => {
          if (res.success) {
            this.tags = res.result
            this.ipagination.total = res.result.length
          } else {
            console.log(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    getInfo(item) {
      return new Promise((resolve, reject) => {
        postAction('tag/list', { tagType: item.dataId }).then(res => {
          if (res.success) {
            resolve(res.result)
          } else {
            console.log(res.message)
          }
        })
      })
    },
    getTags() {
      this.loading = true
      postAction('tag/category/list', { tagCategoryPid: this.activeGroupId })
        .then(res => {
          if (res.success) {
            const list = []
            const promiseArr = res.result.map(v => {
              return this.getInfo(v)
            })
            Promise.all(promiseArr).then(value => {
              value.forEach(n => {
                list.push(...n)
              })
              this.tags = list
              this.ipagination.total = list.length
            })
          } else {
            console.log(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    search() {
      postAction('tag/list', { tagType: this.tagType, tagName: this.tagName })
        .then(res => {
          if (res.success) {
            this.tags = res.result
            this.ipagination.total = res.result.length
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    viewCancel() {
      this.viewVisit = false
    },
    handleView(id) {
      postAction('article/detail', { dataId: id }).then(res => {
        if (res.success) {
          this.viewVisit = true
          this.content = res.result.content
          console.log(this.content)
        } else {
          console.log(res.message)
        }
      })
    },
    handleTableChange(pagination) {
      this.ipagination = pagination
      // this.getTags()
    },
    handleAddContent() {
      this.$refs.serviceModalForm.add()
      this.$refs.serviceModalForm.title = '添加标签'
      this.$refs.serviceModalForm.disableSubmit = false
    },
    handleEditContent(record) {
      record.type = this.activeGroupId
      this.$refs.serviceModalForm.edit(record)
      this.$refs.serviceModalForm.title = '编辑标签'
      this.$refs.serviceModalForm.disableSubmit = false
    },
    isRightMobileNumber(rule, value, callback) {
      if (typeof value === 'undefined' || value === '') {
        callback()
      } else {
        const regex = /^1[3456789]\d{9}$/
        if (!regex.test(value)) {
          this.isAnyWrongData = true
          callback(new Error('请输入正确手机格式'))
        } else {
          this.isAnyWrongData = false
        }
        callback()
      }
    },
    handleSelect(key) {
      this.activeGroupId = key.dataId
      this.ipagination.current = 1
      this.tagType = ''
      this.tagName = ''
      if (key.children) {
        this.getTags()
      } else {
        this.getTag()
      }
    },
    handleAddTags(id) {
      this.$refs.packageModalForm.add(id)
      this.$refs.packageModalForm.title = '新增栏目'
      this.$refs.packageModalForm.disableSubmit = false
    },
    handleEditTags(item) {
      const record = {
        categoryName: item.categoryName,
        dataId: item.dataId,
        categoryDesc: item.categoryDesc,
        categoryPid: item.categoryPid
      }
      this.$refs.packageModalForm.edit(record)
      this.$refs.packageModalForm.title = '编辑栏目'
      this.$refs.packageModalForm.disableSubmit = false
    },
    handleDeleteGroup(id) {
      deleteAction('group/remove', { id }).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.getTagGroups()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleDeleteCheck(id) {
      this.deleteVisible = true
      this.tagId = id
    },
    handleDeleteCheck2(id) {
      this.deleteVisible2 = true
      this.dataId = id
    },
    handleDeleteCancel() {
      this.deleteVisible = false
      this.tagId = ''
    },
    handleDeleteCancel2() {
      this.deleteVisible2 = false
      this.dataId = ''
    },
    handleDelete(id) {
      this.deleteLoading = true
      deleteAction('tag/remove', { tagId: id })
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            if (this.activeGroupId == 17 || this.activeGroupId == 18) {
              this.getTags()
            } else {
              this.getTag()
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.deleteLoading = false
          this.deleteVisible = false
        })
    },
    handleDelete2(id) {
      this.deleteLoading2 = true
      deleteAction('tag/category/remove', { tagCategoryId: id })
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.getCategory()
            this.getTags()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.deleteLoading2 = false
          this.deleteVisible2 = false
        })
    },
    packageModalFormOk() {
      this.getCategory()
    },
    serviceModalFormOk() {
      if (this.activeGroupId == 17 || this.activeGroupId == 18) {
        this.getTags()
      } else {
        this.getTag()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ant-btn {
  margin: 0.2rem;
}

.flup-item {
  margin: 1rem;
  padding: 0.5rem;
  display: flex;
  align-items: center;

  span {
    flex: 1;
  }
}

#tip {
  display: block;

  #warning {
    // margin: 0.3rem;
    text-align: right;
  }
}
.it_search {
  background: white;
  border-top-left-radius: 2px;
  border-top-right-radius: 2px;
  padding: 10px 20px;
  color: rgba(0, 0, 0, 0.85);
}
.it_search > div {
  margin-bottom: 10px;
}
.ant-tag {
  font-size: 14px;
}
/deep/.ant-list-item {
  justify-content: center;
}
/deep/.ant-list-item:hover {
  cursor: pointer;
}
</style>

